using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace FolderSync
{
	class FolderPair
	{
		private string name;

		public string Name
		{
			get { return name; }
			set { name = value; }
		}

		private string leftFolder;

		public string LeftFolder
		{
			get { return leftFolder; }
			set { leftFolder = value; }
		}

		private string rightFolder;

		public string RightFolder
		{
			get { return rightFolder; }
			set { rightFolder = value; }
		}

		public override string ToString()
		{
			return name;
		}
	}

	class FolderPairsManager
	{
		private FolderPairsManager()
		{
			this.folderPairs = new Dictionary<string, FolderPair>();
			this.fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, "FolderSync.xml");
		}

		private static FolderPairsManager instance;

		public static FolderPairsManager Instance
		{
			get { return instance ?? (instance = new FolderPairsManager()); }
			set { instance = value; }
		}

		private string fileName;

		public string FileName
		{
			get { return fileName; }
			//set { fileName = value; }
		}

		private Dictionary<string, FolderPair> folderPairs;

		public ICollection<FolderPair> FolderPairs
		{
			get { return folderPairs.Values; }
		}

		private bool collectionDirty;

		public bool CollectionDirty
		{
			get { return collectionDirty; }
			set { collectionDirty = value; }
		}

		public bool Contains(string name)
		{
			return folderPairs.ContainsKey(name);
		}

		public void Add(FolderPair pair)
		{
			folderPairs.Add(pair.Name, pair);
			collectionDirty = true;
		}

		public void Remove(string name)
		{
			folderPairs.Remove(name);
			collectionDirty = true;
		}

		public void Load()
		{
			XmlDocument document = new XmlDocument();
			if (!File.Exists(fileName)) {
				return;
			}
			document.Load(fileName);
			XmlElement root = document.DocumentElement;
			foreach (XmlElement element in document.GetElementsByTagName("FolderPair")) {
				FolderPair pair = new FolderPair();
				pair.Name = element.GetAttribute("Name");
				pair.LeftFolder = element["LeftFolder"].InnerText;
				pair.RightFolder = element["RightFolder"].InnerText;
				folderPairs.Add(pair.Name, pair);
			}
		}

		public void Save()
		{
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Indent = true;
			using (XmlWriter writer = XmlWriter.Create(fileName, settings)) {
				writer.WriteStartDocument();
				writer.WriteStartElement("FolderPairs");
				foreach (FolderPair pair in folderPairs.Values) {
					writer.WriteStartElement("FolderPair");
					writer.WriteAttributeString("Name", pair.Name);
					writer.WriteElementString("LeftFolder", pair.LeftFolder);
					writer.WriteElementString("RightFolder", pair.RightFolder);
					writer.WriteEndElement();
				}
				writer.WriteFullEndElement();
			}
		}
	}
}
